package com.negative.logic;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.util.Log;
/**
 * this class will get the token for a specific event 
 * it helps get the tixWise purchase widget for the event. 
 *
 */
public class TokenExtractor extends Thread {

	private String token;
	private String html;
	private long evendID;
	private boolean finished = false;
	
	public TokenExtractor(String html, long eventID){
		this.html = html;
		this.evendID = eventID;
	}

	public void run() {
		HttpURLConnection conn = null;
		try{
			URL url;
			url = new URL(html);
			conn = (HttpURLConnection) url.openConnection();
			InputStream is = conn.getInputStream();
			extractToken(is);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (conn != null){
				conn.disconnect();
			}
		}

	}

	private void extractToken(InputStream is) {
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String page = "";
		String inLine;
		try {
			while ((inLine = br.readLine()) != null) {
				page += inLine;
			}
			br.close();
			String searchString = "http://www.tixwise.co.il/event/"+ this.evendID;
			int start = page.indexOf(searchString)+ searchString.length()+1;
			int end = page.indexOf("?",start);
			this.token = page.substring(start,end);
			this.finished = true;
			Log.i("inside", token);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();

		}
	}
	
	public String getToken(){
		return this.token;
	}

	public boolean isFinished() {
		return finished;
	}
}